package server;

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.sql.SQLException;

/**
 * Main sets up the configuration manager and the command manager, and starts
 * the Firewall if it's configured as on. It also sets up the RMI exports.
 * The only object the Server exports via RMI is the FirewallManager. The
 * FirewallManager, in turn, accepts login()'s and creates the appropriate
 * FirewallSession's for the logged-in users.
 */
public class Server {
	public static void main(String args[]) {
		Commands comm = null;
		System.out.println("Context FireWall starting...");
		try {
            // Initialize our configuration and create the command manager.
            // If config says the Firewall is on, turn it on.

			ConfigurationManager config = new ConfigurationManager(
					configFilename);
			comm = new Commands(config);
			if (config.getIsFirewallOn()) {
				comm.turnOn();
			}
		} catch (SQLException e) {
			System.err.println("Error message: " + e.getMessage());
			System.err.println("Error number: " + e.getErrorCode());
			return;
		} catch (Exception e) {
			System.err.println("Error in configuration: " + e.toString());
			e.printStackTrace();
			return;
		}
		try {
            // Create the FirewallManager and export it via RMI.

			FirewallManagerImpl fwManager = new FirewallManagerImpl(comm);
			FirewallManager stub = (FirewallManager) UnicastRemoteObject
				.exportObject(fwManager, 0);

			// Bind the remote object's stub in the registry
			Registry registry = LocateRegistry.getRegistry();
			registry.rebind("FirewallManager", stub);

			System.out.println("Server ready");

            // Never returns unless an error occurred
            
		} catch (Exception e) {
			System.err.println("Server exception: " + e.toString());
			e.printStackTrace();
		}
	}

    /// The configuration file for the Firewall.
	private static final String configFilename = "fw.config";
}
